import router, { asyncPageComponents } from "@/router"
import { defineStore } from "pinia"
import { RouteRecordRaw } from "vue-router"
import Layout from '@/layout/index.vue'
import { menuListApi } from "@/api/system/Permission"

import routes from '@/router/menu'
import { permissionMenusApi } from "@/api/system/Menu"

export const useResourceStore = defineStore<
        string,
        {menus : any[], permissions : string[]},
        {},
        {buildMenus : (data:any[]) => void, getResource : () => Promise<void>, hasPermission : (name:string) => boolean}
    >
('resource', {
    state : () => (
        {
            menus : [],
            permissions : []
        }
    ),

    actions : {
        async getResource() {
            if(import.meta.env.B_USE_ROUTER_MENU == '1') {
                let menus:any[] = []
                const recursionMenus = (source:RouteRecordRaw[], target:any[]) => {
                    source.forEach(route => {
                        if(route.meta.hidden) return

                        let menu:any = {
                            name : route.meta.title,
                            routePath : route.path,
                            routeName : route.name,
                            children : []
                        }

                        if(route.children) {
                            recursionMenus(route.children, menu.children)
                        }

                        target.push(menu)

                    })
                }

                recursionMenus(routes, menus)

                this.menus = menus
            }else {
                const { data } = await permissionMenusApi()
                if(!data) return
    
                this.permissions = data.map(v => v.permission)
    
                this.buildMenus(data)
            }
            
        },

        buildMenus(data:any[]) {
            let menusList = data.filter(v => (v.type === 'PAGE' || v.type === 'FOLD'))
            let menus:any[] = []
            let routes:RouteRecordRaw[] = []
            const componentMap:any = {}

            const recursionMenus = (target:RouteRecordRaw[], menusTarget:any[], path:string, parentId=0) => {
                
                for(let i = 0; i < menusList.length; i ++) {
                    const item = menusList[i]
                    if(parentId == item.parentId) {
                        if(import.meta.env.DEV && item.component !== 'Layout') {
                            componentMap[item.component] = `() => import('@/pages/${item.component}')`
                        }

                        let route:RouteRecordRaw = {
                            path : item.path,
                            name : String(item.id),
                            component : item.component == 'Layout' ? Layout : (import.meta.env.DEV ? () => import('/src/pages/' + item.component) : asyncPageComponents[item.component]),
                            meta : {title : item.name, keepAlive : item.keepAlive, type : item.type},
                            children : []
                        }

                        let menu:any = {
                            ...item,
                            routePath : route.path,
                            routeName : route.name,
                            children : []
                        }

                        target.push(route)

                        if(menu.display == 1) {
                            menusTarget.push(menu)
                        }

                        

                        recursionMenus(route.children, menu.children, route.path + '/', item.id)

                        if(menu.children?.length == 0) {
                            delete menu.children
                        }

                        // if(menu.children?.length == 0) {
                        //     delete menu.children
                        // }else if(menu.children.length == 1) {
                        //     menu.routePath = menu.children[0].routePath
                        //     menu.routeName = menu.children[0].routeName
                        //     menu.name = menu.children[0].name
                        //     delete menu.children
                        // }
                    }
                }
            }

            

            recursionMenus(routes, menus, '/', 0)


            menus.forEach(menu => {
                if(menu.type == 'PAGE') {
                    menu.routeName = menu.routeName + 'new'
                }
            })

            routes.forEach(route => {
                if(route.meta && route.meta.type == 'PAGE') {
                    const component = route.component
                    route.component = Layout


                    route.children[0] = {
                        path : '',
                        meta : route.meta,
                        name : route.name + 'new',
                        component : component,
                        children : []
                    }
                }
            })

            

            

            this.menus.push(...menus)

            routes.forEach(route => {
                
                router.addRoute(route)
            })

            router.onError(a => {
                console.log(a)
            })



            if(import.meta.env.DEV) {
                var s = ''
                console.log('=======================================')
                for(let k in componentMap) {
                    s += `'${k}' : `+ componentMap[k] + ',\n'
                }
                console.log(s)
                console.log('=======================================')
            }
        },

        hasPermission(name:string) {return true
            return this.permissions.includes(name)
        }
    }
})